from django.shortcuts import render

from django.http import HttpResponse

from ..models import Users

from django.contrib.auth.hashers import make_password, check_password

from . IndexViews import uploads
from web.settings import BASE_DIR
import os
from django.contrib.auth.decorators import permission_required


# Create your views here.

# 返回页面
@permission_required('myadmin.insert_users',raise_exception = True)
def useradd(request):

    # return HttpResponse('后端页面')
    return render(request,'myadmin/users/add.html')

# 插入数据
@permission_required('myadmin.insert_users',raise_exception = True)
def userinsert(request):
    try:
        # 接受表单数据
        data=request.POST.dict()
        # 删除csrf代码段
        data.pop('csrfmiddlewaretoken')
        # 打印看看数据
        # print(data)

        # 密码加密
        data['password'] = make_password(data['password'], None, 'pbkdf2_sha256')

        # 是否上传头像

        myfile=request.FILES.get('pic',None)
        #判断是否有文件上传
        if myfile:
            #有文件上传
            data['pic']=uploads(myfile)
        else:
            # 没有文件上传
            data['pic']='/static/pics/user04.jpg'

        # 创建用户
        Users.objects.create(**data)
        # return HttpResponse('hahah')
        # 跳转到列表页
        return HttpResponse('<script>alert("添加成功");location.href="/myadmin/user/index/"</script>')
    except:
        return HttpResponse('<script>alert("添加失败");location.href="/myadmin/user/add/"</script>')



# 用户列表
@permission_required('myadmin.show_users',raise_exception = True)
def userindex(request):
    # 读取数据
    users = Users.objects.exclude(status=2)

    # 接收参数 
    types = request.GET.get('types',None)
    keywords = request.GET.get('keywords',None)
    # 判断是否有搜索条件
    if types:
        if types == 'all':
            # 多字段的查询
            from django.db.models import Q
            users = users.filter(Q(username__contains=keywords)|Q(email__contains=keywords)|Q(phone__contains=keywords)|Q(age__contains=keywords))
        else:
            data = {types+'__contains':keywords}
            users = users.filter(**data)

    # 数据分页
    from django.core.paginator import Paginator
    # 实例化分页对象,参数1,数据列表  参数2 每页显示的条数
    p = Paginator(users, 10)
    # 获取当前的页码数
    page = request.GET.get('page',1)
    # 获取当前页的数据
    userlist = p.page(page)
    # 获取所有的页码列表
    pages = p.page_range

    # 分配数据
    context = {'users':userlist}
    # 加载模板
    return render(request,'myadmin/users/index.html',context)

# 删除用户-----------------物理删除
# def userdel(request):
#     try:
#         # 获取用户ｉｄ
#         uid=request.GET.get('uid')
#         # 获取用户信息
#         ob=Users.objects.get(id=uid)
#         # 删除用户
#         ob.delete()
#         # 返回页面
#         return HttpResponse('<script>alert("删除成功");location.href="/myadmin/user/index/"</script>')
#     except:
#         return HttpResponse('<script>alert("删除失败");location.href="/myadmin/users/index/"</script>')


# 删除 修改状态－－－－－－－－－－－逻辑删除
@permission_required('myadmin.del_users',raise_exception = True)
def userdel(request,uid):
    try:
        # 获取用户对象
        ob = Users.objects.get(id=uid)
        # 修改状态
        ob.status = 2
        # 执行
        ob.save()
        # 跳转到列表页
        return HttpResponse('<script>alert("删除成功");location.href="/myadmin/user/index/"</script>')
    except:
        return HttpResponse('<script>alert("删除失败");location.href="/myadmin/user/index/"</script>')




# 修改获取数据
@permission_required('myadmin.edit_users',raise_exception = True)
def useredit(request,uid):

    # 获取数据
    ob=Users.objects.get(id=uid)
    # 分配数据
    context = {'info':ob}
    # 加载模板
    return render(request,'myadmin/users/edit.html',context)


# 自己的操作
# def userupdate(request):
#     try:
#         # 获取数据
#         ob=Users.objects.get(id=request.POST['uid'])
#         # 修改数据
#         ob.username=request.POST['username']
#         ob.phone=request.POST['phone']
#         ob.email=request.POST['email']
#         ob.sex=request.POST['sex']
#         ob.age=request.POST['age']
#         # 密码加密
#         ob.password= make_password(request.POST['password'], None, 'pbkdf2_sha256')
#         # 是否上传头像
#         myfile=request.FILES.get('pic',None)
#         #判断是否有文件上传
#         if myfile:
#             #有文件上传
#             from . IndexViews import uploads
#             ob.pic=uploads(myfile)
#         else:
#             # 没有文件上传
#             ob.pic='/static/pics/user04.jpg'
#         ob.save()
#         # 返回页面
#         return HttpResponse('<script>alert("修改成功");location.href="/myadmin/user/index/"</script>')
#     except:
#         return HttpResponse('<script>alert("修改失败");location.href="/myadmin/users/index/"</script>')

# 执行修改－－－－－－－－老师教的
@permission_required('myadmin.edit_users',raise_exception = True)
def userupdate(request):
    # 接受数据
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')
    print(data)

    # 获取对象
    ob = Users.objects.get(id=data['id'])
    ob.username = data['username']
    ob.email = data['email']
    ob.age = data['age']
    ob.phone = data['phone']
    ob.sex = data['sex']

    # 判断是否右文件上传
    myfile = request.FILES.get('pic',None)
    if myfile:
        # 有新文件上传,删除原有的头像数据,
        # 判断是否使用的是默认头像
        if ob.pic != '/static/pics/user04.jpg':
            # 删除原来的头像
            os.remove(BASE_DIR+ob.pic)

        # 执行文件的上传.,并更新头像数据
        ob.pic = uploads(myfile)

    # 执行更新
    ob.save()
    # 跳转到列表页
    return HttpResponse('<script>alert("更新成功");location.href="/myadmin/user/index/"</script>')

